package com.lotso.web.module.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lotso.web.common.ReqParam;
import com.lotso.web.common.Result;
import com.lotso.web.common.exception.ParameterException;
import com.lotso.web.module.system.entity.Dict;
import com.lotso.web.module.system.mapper.IDictMapper;
import com.lotso.web.module.system.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ClassName: DictServiceImpl
 * Description:
 * Date: 2018/9/13 11:57 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DictServiceImpl extends ServiceImpl<IDictMapper, Dict> implements IDictService {

    @Autowired
    private IDictMapper dictMapper;

    @Override
    public List<Dict> listByType(String type) {
        Wrapper<Dict> wrapper = new EntityWrapper<Dict>()
                .eq("type", type)
                .orderBy("sort", true);
        return dictMapper.selectList(wrapper);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public Result<Dict> list(ReqParam reqParam) {
        Wrapper<Dict> wrapper = new EntityWrapper<>();
        Page<Dict> dictPage = new Page<>(reqParam.getPage(), reqParam.getLimit());
        String searchValue = Strings.nullToEmpty(reqParam.getSearchValue()).trim();
        if (!Strings.isNullOrEmpty(searchValue)) {
            wrapper.andNew().eq("type", searchValue).or().like("description", searchValue);
            ;
        }
        List<Dict> dictList = dictMapper.selectPage(dictPage, wrapper.orderBy("type", true));
        return new Result<>(dictPage.getTotal(), dictList);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<Dict> list() {
        Wrapper<Dict> wrapper = new EntityWrapper<>();
        return dictMapper.selectList(wrapper.orderBy("type", true));
    }

    @Override
    public boolean add(Dict dict) {

        return dictMapper.insert(dict) > 0;
    }

    @Override
    public boolean update(Dict dict) throws ParameterException {
        return dictMapper.updateById(dict) > 0;
    }

    @Override
    public boolean delete(String dictid) throws ParameterException {
        return dictMapper.deleteById(dictid) > 0;
    }

}
